<?php
/**
 * admin service file Created by PhpStorm.
 * User: wumengmeng
 * Date: 2019/09/12
 * Time: 10:42
 */

namespace Modules\SmallApi\Service;

use DB;
use HiCommon\Repository\OrderMallRepository;
use HiCommon\Repository\OrderMallDetailRepository;
use HiCommon\Repository\GoodsProductRepository;
use HiCommon\Repository\UsersIntegralRepository;
use HiCommon\Repository\UsersRepository;
use HiCommon\Repository\AddressRepository;
use HiCommon\Repository\GoodsSpecsRepository;
use HiCommon\Repository\GoodsRepository;
use HiCommon\Repository\ShopAppriseRepository;


class OrderMallService
{
    /**
     * 提交订单数据验证处理
     */
    public function checkData($data)
    {
        $uid = small_api_user_id();
        if (!$uid) {
            return ['code' => 1, 'smg' => '请登录'];
        } else {
            $data['user_id'] = $uid;
            $data['order_no'] = random_order_sn('GO');
        }
        if (empty($data['shop_id']) && $data['shop_id'] != 0) {
            return ['code' => 1, 'smg' => '门店id不能为空'];
        }
        if (empty($data['goods_id'])) {
            return ['code' => 1, 'smg' => '商品id不能为空'];
        }
        if (empty($data['goods_specs_id'])) {
            return ['code' => 1, 'smg' => '商品规格id不能为空'];
        }
        if (empty($data['goods_num'])) {
            return ['code' => 1, 'smg' => '商品数量不能为空'];
        }
        /*if (empty($data['user_address_id'])) {
            return ['code' => 1, 'smg' => '用户收货地址id不能为空'];
        }*/
        if (empty($data['goods_product_id'])) {
            return ['code' => 1, 'smg' => '产品id不能为空'];
        } else {
            //根据商品id goods_product_id 获取商品信息
            $product = GoodsProductRepository::get_one($data['goods_product_id']);

            $num = $data['goods_num'];
            if ($product && $product->goods_id == $data['goods_id']) {
                if ($num > $product->stock) {
                    return ['code' => 1, 'smg' => '库存不足'];
                }
                $data['goods_price'] = $product->price;               //商品价格
                $data['order_amount'] = $product->price * $num;       //订单总金额
                $data['goods_integral'] = $product->integral;         //商品积分
                $data['order_integral'] = $product->integral * $num;  //订单总积分
                $data['stock'] = $product->stock - $num;              //商品库存
            } else {
                return ['code' => 1, 'smg' => '数据有误'];
            }
        }

        return ['code' => 0, 'smg' => 'ok', 'data' => hi_array_del_null($data)];
    }

    /**
     * 创建订单
     *
     * @param $data
     *
     * @return array|\Illuminate\Http\RedirectResponse
     * @author wumengmeng <wu_mengmeng@foxmail.com>
     */
    public function createOrder($postData)
    {
        try {
            $dataAll = self::checkData($postData);//数据验证处理
            if ($dataAll['code'] == 1) {
                return hello_error($dataAll['smg']);
            }
            $data = $dataAll['data'];

            //添加订单主表数据
            $order = array(
                'order_type' => $data['order_type'],    //  订单类型（1正常订单，2积分订单）
                'order_no' => $data['order_no'],        //  订单编号
                'shop_id' => $data['shop_id'],          //  门店id
                'user_id' => $data['user_id'],          //  买家id
                'order_integral' => $data['order_integral'],    //  订单积分
                'order_amount' => $data['order_amount'],        //  订单金额
                'delivery_price' => $data['delivery_price'],    //  配送费用
                'goods_id' => $data['goods_id'],                //  配送费用
                //'user_address_id' => $data['user_address_id'],  //  收货地址
                'remark' => $data['remark']                     //  买家订单备注
            );

            $res = OrderMallRepository::add_one($order);
            if ($res) {
                //库存处理
                $map = ['id' => $data['goods_product_id'], 'goods_id' => $data['goods_id']];
                $stock = ['stock' => $data['stock']];
                GoodsProductRepository::update_stock($map, $stock);

                //添加订单副表数据（其他信息）
                $orderDetail = array(
                    'order_id' => $res->id,
                    'goods_product_id' => $data['goods_product_id'],
                    'goods_specs_id' => $data['goods_specs_id'],
                    'goods_id' => $data['goods_id'],
                    'goods_num' => $data['goods_num'],
                    'goods_price' => $data['goods_price'],
                    'goods_amount' => $data['order_amount'],
                    'goods_integral' => $data['goods_integral'],
                    'integral_sum' => $data['order_integral'],
                );

                $result = OrderMallDetailRepository::add_one($orderDetail);

                if (!empty($result)) {
                    $res['goods_id'] = $data['goods_id'];
                    return hello_success('成功', $res);
                }
            }

            return hello_error('添加失败');
        } catch (\Exception $exception) {
            return hello_error('失败', [], $exception->getMessage());
        }
    }

    /**
     * 支付订单数据验证处理
     */
    public function checkPayData($data)
    {
        $uid = small_api_user_id();
        if (!$uid) {
            return ['code' => 1, 'smg' => '请登录'];
        } else {
            $data['user_id'] = $uid;
        }
        if (empty($data['order_id'])) {
            return ['code' => 1, 'smg' => '订单id不能为空'];
        }
        if (empty($data['order_no'])) {
            return ['code' => 1, 'smg' => '订单号不能为空'];
        }
        if (empty($data['pay_type'])) {
            return ['code' => 1, 'smg' => '支付类型不能为空'];
        }
        if ($data['pay_type'] > 3) {
            return ['code' => 1, 'smg' => '支付类型错误'];
        }
        if (empty($data['user_address_id'])) {
            return ['code' => 1, 'smg' => '用户收货地址id不能为空'];
        }

        if ($data['pay_type'] == 1) {
            if (empty($data['pay_integral'])) {
                return ['code' => 1, 'smg' => '积分数量不能为空'];
            }
            $user = UsersRepository::get_one((int)$uid);
            if ($user) {
                if ($user->integral < $data['pay_integral']) {
                    return ['code' => 1, 'smg' => '积分不足'];
                } else {
                    //用户扣除订单积分后的剩余积分。
                    $data['user_integral'] = $user->integral - $data['pay_integral'];
                }
            } else {
                return ['code' => 1, 'smg' => '用户不存在'];
            }
        } else {
            if (empty($data['pay_amount'])) {
                return ['code' => 1, 'smg' => '实付金额不能为空'];
            } else {
                //实际支付金额对比验证

            }
        }

        return ['code' => 0, 'smg' => 'ok', 'data' => hi_array_del_null($data)];
    }

    /**
     *订单支付
     */
    public function payOrder($payOrderData)
    {
        try {
            $payData = self::checkPayData($payOrderData);
            if ($payData['code'] == 1) {
                return hello_error($payData['smg']);
            }
            $data = $payData['data'];
            if ($data['pay_type'] == 1) {        //积分支付

                $res = self::payIntegralOrder($data);

                if ($res['code'] == 1) {
                    return hello_error($res['smg']);
                }

                return hello_success($res['smg'], []);

            } elseif ($data['pay_type'] == 2) {  //微信支付

                self::payWeChatlOrder($data);

            } elseif ($data['pay_type'] == 3) {  //支付宝支付

                self::payBaolOrder($data);
            }

        } catch (\Exception $exception) {

            return hello_error('失败', [], $exception->getMessage());
        }
    }

    /**
     * 积分支付数据处理
     */
    public function payIntegralOrder($data)
    {
        $map = ['id' => $data['order_id'], 'order_type' => 2, 'order_no' => $data['order_no'], 'user_id' => $data['user_id']];
        $upArray = [
            'pay_status' => 1,
            'user_address_id' => $data['user_address_id'],
            'pay_time' => date('Y-m-d H:i:s', time())
        ];

        $order = OrderMallRepository::get_one_where($map, ['id', 'goods_id','pay_status']);
        if ($order) {
            if($order->pay_status != 0){
                return ['code' => 1, 'smg' => '该订单已支付'];
            }
            //修改订单状态
            $res2 = OrderMallRepository::edit_one($map, $upArray);

            //修改商品售出的数量
            $sell = $order->getOrderMallDetail['goods_num'];//订单中商品数量
            GoodsRepository::increase_num($order->goods_id, $sell);//修改商品售出的数量

            //扣除用户积分
            $userArray = ['id' => $data['user_id'], 'integral' => $data['user_integral']];
            if (UsersRepository::edit_one((array)$userArray)) {
                //添加用户积分变更记录
                $ntegraLog = [
                    'user_id' => (int)$data['user_id'],
                    'type' => 2,
                    'deduct' => (int)$data['pay_integral'],
                    'surplus' => (int)$data['user_integral'],
                    'order_id' => $data['order_id'],
                    'remarks' => '积分兑换商品'
                ];
                $res1 = UsersIntegralRepository::add_one($ntegraLog);

                if ($res1 && $res2) {
                    return ['code' => 0, 'smg' => '支付成功'];
                } else {
                    return ['code' => 1, 'smg' => '支付失败'];
                };
            }

        }

        return ['code' => 1, 'smg' => '订单不存在'];
    }

    /**
     * 微信支付数据处理
     */
    public function payWeChatlOrder()
    {

    }

    /**
     * 支付宝支付数据处理
     */
    public function payBaolOrder()
    {

    }

    /**
     *  获取指定的订单信息
     *  hinq 2019 09 17
     *
     **/
    public function get_goods_order(int $nId)
    {

        try {
            $address = [];
            //获取当前用户的地址信息
            if (!empty(small_api_user_id())) {
                $arr_where = ['user_id' => small_api_user_id()];
                $arr_option['field'] = ['id', 'user_id', 'username', 'phone', 'province', 'city', 'area', 'address', 'is_defaule'];
                $address = AddressRepository::get_list_by_where((array)$arr_where, (array)$arr_option);
            }

            $arr_options['with'] = ['getGoodsInfo', 'getOrderMallDetail'];
            $arr_options['field'] = ['id', 'order_no', 'shop_id', 'user_id', 'goods_id', 'pay_status', 'order_integral', 'order_amount'];
            $res = OrderMallRepository::get_one((int)$nId, (array)$arr_options);

            //获取商品子类名称
            $specs_list = GoodsSpecsRepository::get_one((int)$res->getOrderMallDetail['goods_specs_id'], (array)['field' => ['name']])->toArray();
            $res->goods_specs_name = $specs_list['name'];

            $data['address'] = $address;
            $data['goods'] = $res;

            return ['state' => 0, 'msg' => 'ok', 'data' => $data, 'error' => ''];

        } catch (\Exception $exception) {
            DB::rollBack();
            return hello_error('失败', [], $exception->getMessage());
        }
    }


    /**
     *  检测用户是否有当前商品的未支付订单
     *  hinq 2019 09 18
     *
     **/
    public function checked_order_one(array $arr_search)
    {

        $arr_where['user_id'] = small_api_user_id();
        $arr_where['goods_id'] = $arr_search['goods_id'];
        $arr_where['pay_status'] = 0;
        $arr_where['order_type'] = 2;
        $arr_option['order'] = ["key" => 'id', 'value' => 'desc'];
        $arr_option['field'] = ["id",'order_integral'];
        $arr_option['with'] = ["getOrderMallDetail"];
        //当前用户 当前商品是否有未支付的订单
        $info = OrderMallRepository::get_one_by_where((array)$arr_where, (array)$arr_option);
        
        if (!empty($info->first())) {
            //当前商品下的同产品、同规格是否存在
            unset($arr_where);
            $arr_where['goods_product_id'] = $arr_search['product_id'];
            $arr_where['goods_specs_id'] = $arr_search['specs_id'];
            $arr_where['goods_id'] = $arr_search['goods_id'];
            $arr_where['order_id'] = $info['id'];
            //如果之前以保存的订单数量不等于现在传过来的数量  更新订单的数量等信息   
            if( $info['get_order_mall_detail']['goods_num'] != $arr_search['goods_num']){

                $integral_sum = $arr_search['goods_num'] * $info['getOrderMallDetail']['goods_integral'];
                $goods_amount = $arr_search['goods_num'] * $info['getOrderMallDetail']['goods_price'];

                $temp['goods_num'] = $arr_search['goods_num'];    //订单数量
                $temp['integral_sum'] = $integral_sum;          //订单总积分
                $temp['goods_amount'] = $goods_amount;          //订单总价格
                //修改订单扩展表数据
                OrderMallDetailRepository::edit_or_create( (array) ['id'=>$info['getOrderMallDetail']['id'] ] , (array) $temp );
                //修改订单表数据
                unset( $temp);
                $temp['order_integral'] = $integral_sum;   //订单总积分
                $temp['order_amount'] = $goods_amount;    //订单总价格
                OrderMallRepository::edit_one( (array) ['id'=>$info['id']] , (array) $temp );
            }
            $count = OrderMallDetailRepository::get_count_by_where((array)$arr_where);
            if ($count >= 1) {  //有未支付的订单
                return ['state' => 1, 'msg' => '有未支付的订单', 'data' => ['id' => $info['id']], 'error' => ''];
            } else {
                return ['state' => 0, 'msg' => 'ok', 'data' => [], 'error' => ''];
            }
        }
        return ['state' => 0, 'msg' => 'ok', 'data' => [], 'error' => ''];
    }


    /**
     * 用户获取积分商城订单列表
     */
    public function getUserGoodsOrderList(array $arr_search)
    {
        $uid = small_api_user_id();//用户id
        if (!$uid) {
            return hello_error('请登录');
        }

        $arr_option['with'] = ['getOrderMallDetail', 'getGoodsInfo'];
        if(!empty($arr_search['delivery_status'])){
            $arr_option['where'] = ['user_id' => $uid, 'delivery_status' => $arr_search['delivery_status']];
        }else{
            $arr_option['where'] = ['user_id' => $uid];
        }
        $listAll = OrderMallRepository::get_list($arr_option, $arr_search)->toArray();

        $page['total'] = $listAll['total'];
        $page['per_page'] = $listAll['per_page'];
        $page['current_page'] = $listAll['current_page'];
        if ($listAll['data']) {
            $list = array();
            foreach ($listAll['data'] as $key => $item) {
                $list[] = array(
                    'order_id' => $item['id'],
                    'order_no' => $item['order_no'],
                    'goods_logo' => $item['get_goods_info']['pic_url']['full_src'],
                    'goods_name' => $item['get_goods_info']['name'],//商品名称
                    'created_at' => $item['created_at'],
                    'order_amount' => $item['order_amount'],
                    'order_integral' => $item['order_integral'],
                    'pay_status' => $item['pay_status'],
                    'status' => $item['status'],
                    'delivery_status' => $item['delivery_status']
                );
            }

            return hello_success('获取成功！', ['list' => $list, 'page' => $page]);
        } else {
            return hello_error('暂无数据');
        }
    }

    /**
     * 用户获取商城订单详情
     */
    public function getUserGoodsOrderDetail($oder_id)
    {
        $arr_option['with'] = ['getOrderMallDetail', 'getGoodsInfo', 'getAddressInfo', 'getExpressInfo'];
        $order = OrderMallRepository::get_one_by_where(['id' => $oder_id], (array)$arr_option);

        if ($order) {
            $detail = $order->toArray();

            return hello_success('获取成功！', $detail);
        } else {
            return hello_error('订单不存在');
        }
    }

    /**
     *  用户评论订单(积分、人民币商品订单评论)
     *  hinq 2019 09 27
     *
     **/
    public function create_order_comment(array $arr_input)
    {
        try {

            if (empty($arr_input['score'])) {
                return hello_error('评分数量不能为空');
            }
            if (!in_array($arr_input['score'], [1, 2, 3, 4, 5])) {
                return hello_error('评分数量错误');
            }
            if (empty($arr_input['order_id'])) {
                return hello_error('订单id不能为空');
            }
            if (empty($arr_input['content'])) {
                return hello_error('评价内容不能为空');
            }
            $arr_input['user_id'] = small_api_user_id();

            //获取当前订单信息
            $order_list = OrderMallRepository::get_one_by_where((array)['id' => $arr_input['order_id'], 'user_id' => $arr_input['user_id']], (array)['field' => ['shop_id', 'id', 'status', 'pay_status']]);
            if (empty($order_list->first())) {
                return hello_error('只能评价自己的订单');
            }
            $order_list = $order_list->toArray();
            if ($order_list['status'] != 2 && $order_list['pay_status'] == 1) {
                return hello_error('该订单暂时不能评价');
            }

            if (empty($order_list['shop_id'])) {
                return hello_error('商家不存在');
            }
            $arr_input['shop_id'] = $order_list['shop_id'];
            $count = ShopAppriseRepository::get_count_by_where((array)['user_id' => $arr_input['user_id'], 'order_id' => $arr_input['order_id']]);
            if ($count >= 1) {
                return hello_error('您已经评价，请勿重复评价');
            }

            //修改订单状态
            $res = OrderMallRepository::edit_one((array)['id' => $arr_input['order_id']], (array)['status' => 3]);
            if (empty($res)) {
                return hello_error('评价失败');
            }
            //添加评论信息
            $res2 = ShopAppriseRepository::add_one((array)$arr_input);
            if (empty($res2)) {
                return hello_error('评价失败');
            }
            return hello_success('评价成功');
        } catch (\Exception $exception) {
            DB::rollBack();
            return hello_error('失败', [], $exception->getMessage());
        }
    }

    /**
     * 用户确认收货
     */
    public function checkOrdertatus($status)
    {
        $res = OrderMallRepository::edit_one((array)['id' => $status['order_id']], (array)['delivery_status' => 3]);
        if (empty($res)) {
            return hello_error('失败');
        }
        return hello_success('成功');
    }

}